<template>
  <view class="chat-wrapper">
    <scroll-view class="messages" scroll-y :scroll-into-view="scrollAnchor">
      <view
        v-for="(msg, index) in messages"
        :key="index"
        :class="['message-item', msg.role === 'user' ? 'user' : 'assistant']"
      >
        <view class="bubble">
          <text v-if="msg.role === 'assistant' && msg.loading">
            <text class="dots">蓄力中<span class="dot">.</span><span class="dot">.</span><span class="dot">.</span></text>
          </text>
          <view v-else>
            <!-- 使用v-html渲染markdown内容 -->
            <rich-text v-if="msg.isMarkdown" :nodes="msg.parsedContent" class="markdown-content"></rich-text>
          <text v-else>{{ msg.display || msg.message }}</text>
          </view>
        </view>
      </view>
      <view :id="scrollAnchor" style="height: 1px"></view>
    </scroll-view>

    <view class="input-area">
      <textarea
        v-model="newMessage"
        placeholder="请输入消息"
        class="input"
        :disabled="isWaiting"
      />
      <button class="send-btn" @tap="send" :disabled="isWaiting">发送</button>
    </view>
  </view>
</template>

<script>
import {
  getChatHistory,
  sendAnalysisMessage,
  sendGeneralMessage
} from '../../service/api.js';

// Markdown解析相关函数
function parseMarkdown(text) {
  if (!text) return '';
  
  // 解析代码块
  text = text.replace(/\`\`\`([\s\S]*?)\`\`\`/g, (match, code) => {
    return '<div class="code-block">' + code.trim() + '</div>';
  });
  
  // 解析行内代码
  text = text.replace(/\`([^\`]+)\`/g, '<code>$1</code>');
  
  // 解析标题
  text = text.replace(/^### (.*$)/gm, '<h3>$1</h3>');
  text = text.replace(/^## (.*$)/gm, '<h2>$1</h2>');
  text = text.replace(/^# (.*$)/gm, '<h1>$1</h1>');
  
  // 解析粗体
  text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  
  // 解析斜体
  text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
  
  // 解析链接
  text = text.replace(/\[([^\]]+)\]\(([^\)]+)\)/g, '<a href="$2">$1</a>');
  
  // 解析列表
  text = text.replace(/^\s*[-\*]\s(.*)$/gm, '<li>$1</li>');
  text = text.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>');
  
  // 解析段落
  text = text.replace(/^(?!<[hou]).+$/gm, '<p>$&</p>');
  
  return text;
}

function isMarkdownContent(text) {
  // 检查是否包含常见的Markdown语法
  const markdownPatterns = [
    /^#\s/,           // 标题
    /\*\*(.*?)\*\*/,  // 粗体
    /\*(.*?)\*/,      // 斜体
    /\`\`\`/,         // 代码块
    /\`.*?\`/,        // 行内代码
    /\[.*?\]\(.*?\)/, // 链接
    /^\s*[-\*]\s/m,   // 列表
  ];
  
  return markdownPatterns.some(pattern => pattern.test(text));
}

export default {
  data() {
    return {
      type: '',
      chatId: '',
      messages: [],
      newMessage: '',
      isWaiting: false,
      scrollAnchor: 'bottom',
      retryCount: 0,
      maxRetries: 3,
      pollingTimer: null,
      pollingInterval: 5000, // 增加轮询间隔到5秒
      maxPollingAttempts: 72, // 最多轮询72次，即6分钟
      currentPollingAttempt: 0,
      pendingMessage: null
    };
  },
  onLoad(options) {
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.redirectTo({ url: '/pages/login/index' });
      return;
    }
    
    this.type = options.type;
    this.chatId = options.chatId || '';
    this.loadHistory();
  },
  onShow() {
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.redirectTo({ url: '/pages/login/index' });
      return;
    }
    
    // 如果有未完成的消息，开始轮询检查
    if (this.pendingMessage) {
      this.startPolling();
    }
  },
  onHide() {
    // 页面隐藏时停止轮询
    this.stopPolling();
  },
  onUnload() {
    // 页面卸载时停止轮询
    this.stopPolling();
  },
  methods: {
    async loadHistory() {
      try {
      const res = await getChatHistory(this.type, this.chatId);
        this.messages = (res.data || []).map(item => {
          const message = item.message || item.content || '';
          const isMarkdown = isMarkdownContent(message);
          return {
        role: item.role || (item.sender === 'user' ? 'user' : 'assistant'),
            message: message,
            display: message,
            loading: false,
            messageId: item.messageId || '',
            isMarkdown: isMarkdown,
            parsedContent: isMarkdown ? parseMarkdown(message) : message
          };
        });
        this.scrollToBottom();
      } catch (err) {
        uni.showToast({
          title: '加载历史消息失败',
          icon: 'none'
        });
      }
    },

    async sendWithRetry(content, aiMsg) {
      try {
        // 发送消息并等待初始响应
        const sendPromise = this.type === 'QUESTION_ANALYSIS'
          ? sendAnalysisMessage(content, this.chatId)
          : sendGeneralMessage(content, this.type, this.chatId);

        const res = await sendPromise;

        if (!res || !res.data) {
          throw new Error('无响应数据');
        }

        // 更新会话ID
        this.chatId = res.data?.conversationId || this.chatId;
        
        // 如果有直接返回的回复，立即显示
        if (res.data?.data && res.data.data !== '（无回复）') {
          const reply = res.data.data;
          aiMsg.message = reply;
          aiMsg.display = reply;
          aiMsg.loading = false;
          aiMsg.messageId = res.data?.messageId;
          this.pendingMessage = null;
          this.isWaiting = false;
          this.scrollToBottom();
          return;
        }
        
        // 如果没有直接返回回复，开始轮询
        aiMsg.messageId = res.data?.messageId;
        this.pendingMessage = {
          content,
          messageId: aiMsg.messageId
        };
        
        aiMsg.display = '正在思考中...';
        this.startPolling();

      } catch (err) {
        console.error('发送消息失败:', err);
        
        // 如果是网络错误，尝试重试
        if (err.errMsg && err.errMsg.includes('fail')) {
          if (this.retryCount < this.maxRetries) {
            this.retryCount++;
            aiMsg.display = `正在重试(${this.retryCount}/${this.maxRetries})...`;
            await new Promise(resolve => setTimeout(resolve, 2000));
            return this.sendWithRetry(content, aiMsg);
          }
        }

        // 显示错误信息
        aiMsg.display = '发送失败，请重试';
        aiMsg.loading = false;
        this.isWaiting = false;
        
        uni.showToast({
          title: '网络请求失败，请检查网络连接',
          icon: 'none',
          duration: 2000
        });
      }
    },

    async checkPendingMessage() {
      if (!this.pendingMessage) return;
      
      try {
        const res = await getChatHistory(this.type, this.chatId);
        if (!res || !res.data) return false;
        
        const messages = res.data || [];
        
        // 查找最近的回复
        for (let i = messages.length - 1; i >= 0; i--) {
          const message = messages[i];
          if (message.role === 'assistant' || message.sender === 'assistant') {
            const content = message.message || message.content;
            if (!content || content === '（无回复）') continue;
            
            const index = this.messages.findIndex(m => m.loading);
            if (index !== -1) {
              const isMarkdown = isMarkdownContent(content);
              this.messages[index] = {
                role: 'assistant',
                message: content,
                display: content,
                loading: false,
                messageId: message.messageId,
                isMarkdown: isMarkdown,
                parsedContent: isMarkdown ? parseMarkdown(content) : content
              };
              this.pendingMessage = null;
              this.isWaiting = false;
      this.scrollToBottom();
              return true;
            }
          }
        }
        return false;
      } catch (err) {
        console.error('检查消息状态失败:', err);
        return false;
      }
    },

    startPolling() {
      this.stopPolling();
      this.currentPollingAttempt = 0;
      
      const poll = async () => {
        if (!this.pendingMessage || this.currentPollingAttempt >= this.maxPollingAttempts) {
          this.stopPolling();
          if (this.currentPollingAttempt >= this.maxPollingAttempts) {
            const index = this.messages.findIndex(m => m.loading);
            if (index !== -1) {
              this.messages[index].display = '响应时间过长，请重试';
              this.messages[index].loading = false;
            }
            this.pendingMessage = null;
            this.isWaiting = false;
            
            uni.showToast({
              title: '响应超时，请重新发送',
              icon: 'none',
              duration: 2000
            });
          }
          return;
        }

        this.currentPollingAttempt++;
        const success = await this.checkPendingMessage();
        
        if (success) {
          this.stopPolling();
        } else if (this.currentPollingAttempt % 12 === 0) { // 每分钟提示一次
          const index = this.messages.findIndex(m => m.loading);
          if (index !== -1) {
            this.messages[index].display = '正在处理中，请耐心等待...';
          }
        }
      };

      this.pollingTimer = setInterval(poll, this.pollingInterval);
      poll(); // 立即执行一次
    },

    stopPolling() {
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer);
        this.pollingTimer = null;
      }
    },

    async send() {
      const content = this.newMessage.trim();
      if (!content || this.isWaiting) return;

      this.messages.push({ role: 'user', message: content });
      this.newMessage = '';
      this.isWaiting = true;
      this.scrollToBottom();

      const aiMsg = {
        role: 'assistant',
        message: '',
        display: '',
        loading: true
      };
      this.messages.push(aiMsg);
      this.scrollToBottom();

      this.retryCount = 0;
      await this.sendWithRetry(content, aiMsg);
    },

    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollAnchor = 'bottom-' + Date.now();
      });
    }
  }
};
</script>

<style>
.chat-wrapper {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f3f6ff;
}
.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
}
.message-item {
  margin-bottom: 20rpx;
  display: flex;
}
.message-item.user {
  justify-content: flex-end;
}
.message-item.assistant {
  justify-content: flex-start;
}
.bubble {
  max-width: 70%;
  padding: 20rpx;
  border-radius: 20rpx;
  font-size: 30rpx;
  background-color: #ffffff;
  color: #333;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
}
.message-item.user .bubble {
  background-color: #5983ff;
  color: white;
}
.input-area {
  display: flex;
  padding: 20rpx;
  background: #fff;
  border-top: 1rpx solid #ddd;
}
.input {
  flex: 1;
  font-size: 30rpx;
  padding: 10rpx;
  background: #f9f9f9;
  border-radius: 10rpx;
  margin-right: 10rpx;
}
.send-btn {
  background-color: #5983ff;
  color: white;
  padding: 10rpx 20rpx;
  font-size: 30rpx;
  border-radius: 10rpx;
}
.dot {
  animation: blink 1.4s infinite both;
  margin-left: 2rpx;
}
.dot:nth-child(2) {
  animation-delay: 0.2s;
}
.dot:nth-child(3) {
  animation-delay: 0.4s;
}
@keyframes blink {
  0%, 20% { opacity: 0; }
  50% { opacity: 1; }
  100% { opacity: 0; }
}

/* Markdown样式 */
.markdown-content {
  line-height: 1.6;
}

.markdown-content h1 {
  font-size: 40rpx;
  margin: 20rpx 0;
}

.markdown-content h2 {
  font-size: 36rpx;
  margin: 16rpx 0;
}

.markdown-content h3 {
  font-size: 32rpx;
  margin: 14rpx 0;
}

.markdown-content p {
  margin: 10rpx 0;
}

.markdown-content code {
  background-color: #f0f0f0;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  font-family: monospace;
}

.markdown-content .code-block {
  background-color: #f0f0f0;
  padding: 20rpx;
  border-radius: 8rpx;
  font-family: monospace;
  white-space: pre-wrap;
  margin: 10rpx 0;
}

.markdown-content ul {
  padding-left: 40rpx;
  margin: 10rpx 0;
}

.markdown-content li {
  margin: 5rpx 0;
}

.markdown-content a {
  color: #5983ff;
  text-decoration: underline;
}

.markdown-content strong {
  font-weight: bold;
}

.markdown-content em {
  font-style: italic;
}
</style>
